﻿using UnityEngine;
using System.Collections;
using System.IO;

public partial class CyberU
{
    #region Sound and Music

    public static (string path, AudioType type) GetAudioTypeOrTrans(string filePath)
    {
        string extension = Path.GetExtension(filePath).ToLower();

        switch (extension)
        {
            case ".wav":
                return (filePath, AudioType.WAV);
            case ".mp3":
                return (filePath, AudioType.MPEG);
            case ".ogg":
                return (filePath, AudioType.OGGVORBIS);
            default:
                // Debug.LogWarning($"Unsupported audio format: {extension}. Attempting to convert to WAV.");
                string convertedPath = ConvertToWav(filePath);
                return (convertedPath, AudioType.WAV);
        }
    }

    public static string ConvertToWav(string inputFilePath)
    {
        if (!System.IO.File.Exists(inputFilePath))
        {
            Debug.LogError("Input file does not exist.");
            return null;
        }

        string fileName = System.IO.Path.GetFileNameWithoutExtension(inputFilePath);
        string safeFileName = fileName + ".wav";
        string outputDir = "Assets/Resources/temp/wav";
        string outputFilePath = System.IO.Path.Combine(outputDir, safeFileName);
        if (!System.IO.Directory.Exists(outputDir))
        {
            System.IO.Directory.CreateDirectory(outputDir);
        }
        var psi = new System.Diagnostics.ProcessStartInfo
        {
            FileName = "ffmpeg", // 确保 ffmpeg 可执行文件位于系统的 PATH 环境变量中，或者提供完整路径
            Arguments = $"-i \"{inputFilePath}\" -y \"{outputFilePath}\"",
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            UseShellExecute = false,
            CreateNoWindow = true
        };
        // Debug.Log($"FFmpeg command: {psi.FileName} {psi.Arguments}");
        using (var process = new System.Diagnostics.Process { StartInfo = psi })
        {
            // Debug.Log("Starting FFmpeg process");
            process.Start();
            // return (outputFilePath);
            process.BeginOutputReadLine();
            process.BeginErrorReadLine();
            process.WaitForExit();

            if (process.ExitCode == 0)
            {
                // Debug.Log($"Successfully converted to: {outputFilePath}");
                return outputFilePath;
            }
            else
            {
                Debug.LogError($"Failed to convert. Error: {process.StandardError.ReadToEnd()}");
                return null;
            }
        }
    }


    #endregion
}